import axios from 'axios';

import { showToast } from 'vant';

import qs from 'qs';
import { newDecrypt, newEncrypt } from '../util/aes';
import { _localUserInfo } from '../util/authUserInfo/userInfo';


const instance = axios.create({
    // localUrl, //baseURL会在发起请求的时候自动拼接在url前面
    timeout: 500000,
});

instance.interceptors.request.use(
    //请求拦截 统一加密
    async (config) => {
        if (config.method === 'post') {
            config.data = qs.parse(config.data);
            let isEncrypted = config.data.isEncrypted;
            let jsonParam;
            if (isEncrypted === '1') {
                jsonParam = await newEncrypt(JSON.stringify(config.data.jsonParam));
            } else {
                jsonParam = config.data.jsonParam;
            }
            config.data = qs.stringify({
                jsonParam: JSON.stringify({
                    jsonParam,
                    isEncrypted,
                }),
            });
        } else {
            let isEncrypted = config.params.isEncrypted;
            let jsonParam = isEncrypted
                ? newEncrypt(config.params.jsonParam)
                : config.params.jsonParam;
            config.params = {
                jsonParam: JSON.stringify({
                    jsonParam,
                    isEncrypted,
                }),
            };
        }
        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
);

instance.interceptors.response.use(
    //响应拦截
    async function (res) {
        // console.log(res);
        let code = res.data.code;
        let isEncrypted = res.data.isEncrypted;
        if (code == '0000') {
            if (isEncrypted == '1') {
                try {
                    let enc = await newDecrypt(res.data.result);
                    return Promise.resolve(JSON.parse(enc));
                } catch (error) {
                    console.error('！！三方接口无返回或三方接口异常！！');
                    console.log(error);
                }
            } else {
                try {
                    return Promise.resolve(JSON.parse(res.data.result));
                } catch (error) {
                    console.error('！！三方接口无返回或三方接口异常！！');
                    console.log(error);
                }
            }
        } else if (code == '0001') {
            console.error('参数为空！');
            return false;
        } else if (code == '5000') {
            showToast('当前使用人数太多，请稍后再试～');
            return false;
        } else if (code == '9999') {
            console.error('后端服务异常！');
            return false;
        }
    },
    function (err) {
        // console.log('ss')
        let { response } = err;
        if (response) {
            // 服务器返回结果
            switch (response.status) {
                //判断错误编码
                case 401:
                    break;
                case 403:
                    break;
                case 404: //
                    break;
            }
        } else {
            // console.log('ss')
            // 服务器崩溃或者断网
            if (!window.navigator.onLine) {
                // 断网处理  可以跳转到断网页面
                return;
            }
        }
        return Promise.reject(err);
    }
);

class HTTP {
    static post(url: string, jsonParam: object, type?: string): Promise<any> {
        // let userInfo = _localUserInfo();
        // if (!(type && type === 'uploadFile')) {
        //     jsonParam = qs.stringify(jsonParam);
        // }
        return new Promise((resolve, reject) => {
            instance
                .post(url, jsonParam, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;',
                        // userKey: userInfo.zwdtsw_user_id,
                    },
                })
                .then((res) => {
                    resolve(res);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }
    static get(url: string, jsonParam: object): Promise<any> {
        return new Promise((resolve, reject) => {
            instance
                .get(url, jsonParam)
                .then((res) => {
                    resolve(res);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }
    static uploadFile(url: string, jsonParam: object) {
        jsonParam = qs.stringify(jsonParam);
        return new Promise((resolve, reject) => {
            instance
                .post(url, jsonParam, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;',
                    },
                })
                .then((res) => {
                    resolve(res);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }
}

export { HTTP };
